<!DOCTYPE html>
<html>

<head>
    <title>募捐详情</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../../element/element.css">
    <script src="../../element/vue.js"></script>
    <script src="../../element/index.js"></script>
    <script src="../../js/axios.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="../../css/dontions.css">
<!--  -->

<body>

    <body>
        <div id="app">
            <el-dialog :visible.sync="reportFormVisible" title="举报表单">
                <el-form :model="reportForm" :rules="reportFormRules" ref="reportForm">
                    <el-form-item label="举报原因" prop="reportReason">
                        <el-input v-model="reportForm.reportReason"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="reportForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="详细情况说明" prop="reportInfo">
                        <el-input v-model="reportForm.reportInfo"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="reportFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitReport">确定</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

            <el-card>
                <el-button type="primary" @click="save()">返回</el-button>
                <el-button @click="showReportForm" style="text-align: right;">我要举报</el-button>

                <h2 slot="header" style="text-align: center;">募捐详情</h2>
                <div style="display: flex; justify-content: right;">

                    <div style="display: flex; justify-content: right;">
                        <el-button type="primary" icon="el-icon-arrow-left" style="margin-right: auto;"
                            @click="goToPreviousPage">上一页</el-button>
                        <el-button type="primary" @click="goToNextPage">下一页<i
                                class="el-icon-arrow-right el-icon--right"></i></el-button>
                    </div>
                </div>


                <div v-for="detail in donationDetails" :key="detail.id">

                    <el-row>
                        <el-col :span="12">
                            <img :src="`http://${detail.donationImage}`" alt="募捐图片" width="300px" height="300px">
                            <p>&nbsp&nbsp&nbsp别名：{{ detail.alias }}&nbsp&nbsp&nbsp年龄：{{ detail.age }} </p>

                            <el-button :disabled="status != 5" type="primary" @click="showDonateDialog">捐款</el-button>

                            <!-- 捐款对话框 -->
                            <el-dialog title="捐款" :visible.sync="dialogVisible">
                                <el-form ref="donationForm" :model="donationForm" label-width="120px">
                                    <el-form-item label="捐款金额">
                                        <el-input v-model="donationForm.amount"></el-input>
                                    </el-form-item>
                                </el-form>
                                <span slot="footer" class="dialog-footer">
                                    <el-button @click="dialogVisible = false">取消</el-button>
                                    <el-button type="primary" @click="confirmDonation">确定</el-button>
                                </span>
                            </el-dialog>
                        </el-col>
                        <el-col :span="12">
                            <p>目标金额：{{ detail.donationAmount }}</p>
                            <p>募捐金额原因：{{ detail.amountReason }}</p>
                            <p>截止日期：{{ detail.deadline }}</p>
                            <p>募捐时间原因:{{ detail.timeReason }}</p>
                        </el-col>
                    </el-row>
                </div>
                <el-row v-if="donationsInfo">
                    <el-col :span="24">
                        <p>申请缘由：{{ donationsInfo.incident }}</p>
                        <p>家庭情况：{{ donationsInfo.family }}</p>
                        <p>财务状况：{{ donationsInfo.finance }}</p>
                        <p>预期目标：{{ donationsInfo.status }}</p>
                    </el-col>
                </el-row>
                <!-- 积分表认证 -->
                <h3 style="text-align: center">积分认证情况</h3>
                <el-table :data="pointsList" style="width: 100%" @selection-change="onSelectionChange">
                    <!-- 选择列 -->
                    <!-- 其他列 -->
                    <el-table-column prop="pointsRulesId" label="ID"></el-table-column>
                    <el-table-column prop="ruleTitle" label="标题"></el-table-column>
                    <el-table-column prop="pointsValue" label="分值"></el-table-column>
                    <el-table-column prop="details" label="具体描述"></el-table-column>
                </el-table>

                <!-- 总分 -->
                <h4>总分: {{ totalPoints }}</h4>
                <el-row class="flex-container">
                    <el-row class="number" :gutter="20">
                        <el-col>
                            <div class="box">募捐目标:<br><br><br><span class="large-font">{{ donationDetails[0] ?
                                    donationDetails[0].donationAmount : '' }}</span></div>
                        </el-col>
                        <el-col>
                            <el-button class="box" @click="fetchDonationRecords">
                                已募捐金额:<br><br><br>
                                <span class="large-font">{{ donationDetails[0] ? donationDetails[0].donatedAmount : ''
                                    }}</span>
                            </el-button>
                        </el-col>
                        <el-col>
                            <div class="box">募捐截止时间:<br><br><br><span class="large-font">{{ donationDetails[0] ?
                                    donationDetails[0].deadline : '' }}</span></div>
                        </el-col>
                        <el-col>
                            <el-button class="box" @click="fetchFundingDetails">
                                已拨款金额:<br><br><br>
                                <span class="large-font">{{ donationDetails[0] ? donationDetails[0].expenseAmount:
                                    ''}}</span>
                            </el-button>
                        </el-col>
                    </el-row>

                    <el-row class="buttons">
                        <el-col>
                            <el-button type="primary" icon="el-icon-s-operation" @click="downloadDataTemplate">
                                下载募捐资料模板
                            </el-button>

                            <el-button type="primary" icon="el-icon-download" @click="getdonationIdFile">
                                下载募捐证明
                            </el-button>
                        </el-col>
                    </el-row>

                </el-row>
                <el-col v-if="isTableVisible">
                    <el-table :data="donationRecords">
                        <el-table-column prop="donationRecordsId" label="募捐单号"></el-table-column>
                        <el-table-column prop="userId" label="募捐人">
                            <template slot-scope="scope">
                                用户{{ scope.row.userId}}号
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="userId" label="募捐人"></el-table-column> -->
                        <el-table-column prop="donationTime" label="捐款时间"></el-table-column>
                        <el-table-column prop="donationAmount" label="捐款金额"></el-table-column>
                    </el-table>
                </el-col>
                <el-col v-if=" isExpenseTableVisible">
                    <el-table :data="fundingDetails">
                        <el-table-column prop="requestMoneyId" label="拨款单号"></el-table-column>
                        <el-table-column prop="money" label="申请金额"></el-table-column>
                        <el-table-column prop="time" label="拨款时间"></el-table-column>
                        <el-table-column prop="reason" label="拨款原因"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <div>
                                    <el-button @click="downloadFile(scope.row)">下载文件</el-button>
                                </div>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-col>
            </el-card>

        </div>
        <script>
            var userId = localStorage.getItem('userId');
            var donationIds = JSON.parse(localStorage.getItem("donationIds"));
            var DonationId = localStorage.getItem('donationId');
            var index = localStorage.getItem('index');
            new Vue({
                el: '#app',
                data() {
                    return {
                        reportForm: {
                            reportReason: '',
                            phone: '',
                            reportInfo: ''
                        },
                        reportFormRules: {
                            reportReason: [
                                { required: true, message: '请输入举报原因', trigger: 'blur' }
                            ],
                            phone: [
                                { required: true, message: '请输入手机号码', trigger: 'blur' },
                                { pattern: /^1\d{10}$/, message: '手机号码格式不正确', trigger: 'blur' }
                            ],
                            reportInfo: [
                                { required: true, message: '请填写详细情况说明', trigger: 'blur' }
                            ]
                        },
                        status:-1,
                        reportFormVisible: false,
                        pointsId: "",
                        isPointsRules: "",
                        pointsList: [], // 积分列表数据
                        selectedRows: [], // 选择的行数据
                        userId: '',
                        isExpenseTableVisible: false,
                        isTableVisible: false,
                        donationDetails: [],
                        donationsInfo: null,
                        donationRecords: [],
                        fundingDetails: [],
                        dialogVisible: false,
                        dialog: false,
                        donationForm: {
                            amount: ''
                        }
                    }
                },
                mounted() {
                    this.currentUser = localStorage.getItem('userId');
                },
                methods: {

                    submitReport() {
                        axios.post('http://localhost:8888/api/report/create', {
                            userId: userId,
                            donationId: DonationId,
                            reportReason: this.reportForm.reportReason,
                            reportReasonInfo: this.reportForm.reportInfo,
                            phone: this.reportForm.phone
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.reportFormVisible = false; // 关闭对话框
                                    this.$message.success('举报表单提交成功');
                                } else {
                                    console.log(response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('提交失败:', error);
                            });
                    },
                    showReportForm() {
                        this.reportFormVisible = true;
                    },
                    save() {
                        window.location.href = "donationList.html"
                    },
                    goToPreviousPage() {
                        // var index = localStorage.getItem('index');
                        // alert(index)
                        if (parseInt(index) === 0) {
                            this.$message.error('已经到第一页了！')
                            return;
                        } else {
                            localStorage.setItem("donationId", donationIds[parseInt(index) - 1]);
                            localStorage.setItem("index", parseInt(index) - 1);
                            window.location.href = "userDonation.html"
                        }
                        // 上一页的逻辑处理代码
                    },
                    goToNextPage() {

                        if (parseInt(index) === donationIds.length - 1) {
                            this.$message.error('已经到最后一页了！')
                            return;
                        }
                        else {
                            // alert(index)
                            console.log(donationIds);
                            localStorage.setItem("donationId", donationIds[parseInt(index) + 1]);
                            localStorage.setItem("index", parseInt(index) + 1);
                            window.location.href = "userDonation.html"
                        }
                        // 上一页的逻辑处理代码
                    },
                    search() {
                        // alert(this.isPointsRules)
                        axios.get('http://localhost:8888/api/donation/getByIsPointsRules', {
                            params: {
                                isPointsRules: this.isPointsRules
                            }
                        })
                            .then(response => {
                                const result = response.data;
                                if (result.code === 0) {
                                    this.pointsList = result.data;
                                } else {
                                    console.error(result.message);
                                    console.log("查询失败");
                                }
                            })
                            .catch(error => {
                                console.error(error);
                                // 处理错误的逻辑...
                            });
                    },
                    //获取募捐详情
                    getDonationDetails() {
                        axios.get('http://localhost:8888/api/donation/get', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                                this.status = response.data.data.status
                                this.isPointsRules = response.data.data.isPointsRules
                                this.pointsId = response.data.data.pointsId
                                data = response.data.data
                                if (data.deadline) {
                                    data.deadline = new Date(data.deadline).toLocaleDateString(); // 格式化为年月日
                                }
                                this.donationDetails.push(data);
                                this.search()
                                if(this.status===6){
                                    this.$message.success("此募捐活动已结束")
                                }
                                else if(this.status===7){
                                    this.$message.error("此募捐活动状态异常")
                                }
                            })
                            .catch(error => {
                                console.error(error);
                            });
                        axios.get('http://localhost:8888/api/donation/getDonationsInfo', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.donationsInfo = response.data.data;
                                } else {
                                    console.error('Request failed: ' + response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Request error: ' + error);
                            });
                    },
                    // 获取捐赠记录
                    fetchDonationRecords() {
                        if (this.isTableVisible) {
                            this.isTableVisible = false;
                            return;
                        }

                        axios.get('http://localhost:8888/api/donation/getDonationRecords', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.donationRecords = response.data.data;
                                    this.isTableVisible = true;

                                    this.donationRecords = this.donationRecords.map(record => {
                                        if (record.donationTime) {
                                            let donationTime = new Date(record.donationTime);
                                            record.donationTime = donationTime.toLocaleDateString(); // 格式化为年月日
                                        }
                                        return record;
                                    });


                                } else {
                                    console.error('查询失败:', response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('请求失败:', error);
                            });
                    },
                    //拨款详情
                    fetchFundingDetails() {
                        if (this.isExpenseTableVisible) {
                            this.isExpenseTableVisible = false;
                            return;
                        }
                        axios.get('http://localhost:8888/api/funding/queryByDonationId', {
                            params: {
                                donationId: DonationId, // 这里替换为实际的募捐活动 ID
                                isPerson: 0 // 这里替换为实际的是否为本人的值
                            }
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.fundingDetails = response.data.data;
                                    this.isExpenseTableVisible = true;
                                    this.fundingDetails = this.fundingDetails.map(record => {
                                        if (record.time) {
                                            let time = new Date(record.time);
                                            record.time = time.toLocaleDateString(); // 格式化为年月日
                                        }
                                        return record;
                                    });
                                } else {
                                    console.error('查询失败:', response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('请求失败:', error);
                            });
                    },
                    //下载拨款文件
                    downloadFile(row) {
                        const fundingId = row.requestMoneyId; // 这里的fundingId应该根据实际情况获取
                        // 构建查询参数对象
                        const params = new URLSearchParams();
                        params.append('fundingId', fundingId);

                        axios.get(
                            'http://localhost:8888/api/funding/downloadReport',
                            {
                                params: params
                            },
                            'blob' // 表明返回服务器返回的数据类型
                        )
                            .then((response) => {
                                const url = window.URL.createObjectURL(new Blob([response.data]));
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', '用钱报告.pdf');
                                document.body.appendChild(link);
                                link.click();
                            })
                            .catch((error) => {
                                console.log(error);
                            });
                    },
                    //下载募捐资料
                    getdonationIdFile() {
                        fetch(`http://localhost:8888/api/donation/downloadData?donationId=${DonationId}`)
                            .then(response => response.blob())
                            .then(blob => {
                                const url = window.URL.createObjectURL(blob);
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', 'dontionFile.pdf');
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                            })
                            .catch(error => {
                                this.$message.error("文件不存在");
                                console.error('Error downloading file:', error);
                                // 处理下载失败的情况
                            });
                    },
                    //下载募捐资料模板
                    downloadDataTemplate() {
                        axios.get('http://localhost:8888/api/points/download', {
                            responseType: 'blob',
                            params: {
                                pointsId: this.pointsId // 替换为您需要下载的文件对应的pointsId
                            }
                        })
                            .then(response => {
                                const url = window.URL.createObjectURL(new Blob([response.data]));
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', 'points.doc');
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                                window.URL.revokeObjectURL(url);
                            })
                            .catch(error => {
                                console.error('下载失败', error);
                            });
                    },
                    //捐款
                    showDonateDialog() {
                        this.dialogVisible = true;

                    },
                    //已拨款金额按钮
                    showDialog() {
                        this.dialog = true;
                    },
                    confirmDonation() {
                        var userId = localStorage.getItem('userId');
                        const requestData = {
                            userId: userId, // 替换为实际的用户ID
                            donationId: DonationId, // 替换为实际的募捐ID
                            amount: this.donationForm.amount
                        };
                        axios.post('http://localhost:8888/api/money/contribution', requestData)
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.dialogVisible = false; // 关闭对话框
                                    this.$message.success('捐款成功');
                                    // 在这里可以根据业务逻辑进行其他操作
                                } else {
                                    this.$message.error('余额不足，捐款失败');
                                }
                            })
                            .catch(error => {
                                console.error('捐款请求失败', error);
                                this.$message.error('捐款请求失败，请重试');
                            });
                            document.location.reload() 
                    },
                },
                created() {
                    // 创建一个Promise链
                    Promise.resolve()
                    // 第一个任务：调用getDonationDetails函数
                    return this.getDonationDetails();
                },
                computed: {
                    totalPoints() {
                        return this.pointsList.reduce((total, item) => total + item.pointsValue, 0);
                    },
                },

            });
        </script>
    </body>

</html>